package com.ruizhong.integratedmediawithoutc.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruizhong.integratedmediawithoutc.config.DefaultAssetsPathProvider;
import com.ruizhong.integratedmediawithoutc.entity.TSystem;
import com.ruizhong.integratedmediawithoutc.service.TSystemService;
import com.ruizhong.integratedmediawithoutc.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

@RestController
@RequestMapping("/system/api")
@CrossOrigin
public class SystemController {

    @Autowired
    private TSystemService tSystemService;

    public static String share_dir;

    @PostConstruct
    public void init(){
//        启动服务器
        HashMap<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("command", CMD.Start.ordinal());
        conditionMap.put("user_name","Admin");
        conditionMap.put("data",null);
        Map<String, Object> resMap = TCPUtil.send(conditionMap);
//        获取系统配置
        Result config = getConfig(null);
        System.out.println(config.getData());
        HashMap<String, Object> data =(HashMap<String, Object>) config.getData();
//        HashMap<String, Object> data = (HashMap<String, Object>) resMap.get("data");
        data =(HashMap<String, Object>)  data.get("data");
        String server_dir = data.get("server_dir").toString();
        share_dir = data.get("share_dir").toString();
        server_dir = server_dir.replace("\\", "/") + "/";
        HashMap<String, String> map = new HashMap<>();
        map.put("path",server_dir);
        updateAssetsPath(map);
    }


    @Autowired
    private DefaultAssetsPathProvider pathProvider;

    @PostMapping("/update-path")
    public String updateAssetsPath(@RequestBody Map<String, String> request) {
        String newPath = request.get("path");
        newPath = newPath.replace("*", "/");
        pathProvider.updateAssetsPath(newPath);
        return "资源路径已更新为: " + newPath;
    }

    @GetMapping("/current-path")
    public String getCurrentPath() {
        return "当前资源路径: " + pathProvider.getCurrentAssetsPath();
    }

    @GetMapping("/getConfig/{userName}")
    public Result getConfig(@PathVariable(value = "userName") String userName){
        TSystem config = tSystemService.getConfig();
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("server_dir",config.getServerDir());
        dataMap.put("share_dir",config.getShareDir());
        dataMap.put("code_type",config.getCodeType());
        dataMap.put("censor",config.getCensor());
        HashMap<String, Object> resMap = new HashMap<>();
        resMap.put("data",dataMap);
        return new Result(ResultCode.success,null,resMap);
    }

    @GetMapping("/startServer/{userName}")
    public Result startServer(@PathVariable(value = "userName") String userName){
        HashMap<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("command",CMD.Start.ordinal());
        conditionMap.put("user_name",userName);
        conditionMap.put("data",null);
        Map<String, Object> resMap = TCPUtil.send(conditionMap);
        return new Result(ResultCode.success,null,resMap);
    }

    @GetMapping("/stopServer/{userName}")
    public Result stopServer(@PathVariable(value = "userName") String userName){
        HashMap<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("command",CMD.Stop.ordinal());
        conditionMap.put("user_name",userName);
        conditionMap.put("data",null);
        Map<String, Object> resMap = TCPUtil.send(conditionMap);
        return new Result(ResultCode.success,null,resMap);
    }

    @PostMapping("/saveConfig")
    public Result saveConfig(@RequestBody Map<String,Object> conditionMap){
        ArrayList<Map<String,Object>> data = (ArrayList) conditionMap.get("data");
        Map<String, Object> configMap = data.get(0);
        tSystemService.saveConfig(configMap);
        HashMap<String, String> map = new HashMap<>();
        share_dir = configMap.get("share_dir").toString();
        map.put("path",configMap.get("server_dir").toString());
        updateAssetsPath(map);
        return new Result(ResultCode.success,null,null);
    }

    @PostMapping("/setSRSIp")
    public Result setSRSIp(@RequestBody Map<String,String> conditionMap){
        SRSUtil.setSrsServer_ip(conditionMap.get("ip"));
        return new Result(ResultCode.success,"成功",null);
    }

    @GetMapping("/getSRSIp")
    public Result getSRSIp(){
        return new Result(ResultCode.success,"成功", SRSUtil.srsServer_ip);
    }

    @PostMapping("/setPushStreamIp")
    public Result setPushStreamIp(@RequestBody Map<String,String> conditionMap){
        TCPUtil.setPushStreamServerIp(conditionMap.get("ip"));
        return new Result(ResultCode.success,"成功",null);
    }

    @GetMapping("/getPushStreamIp")
    public Result getPushStreamIp(){
        return new Result(ResultCode.success,"成功",TCPUtil.pushStreamServerIp);
    }


    @GetMapping("/setPushStreamIpWithGet")
    public Result setPushStreamIpWithGet(@RequestParam String ip){
        TCPUtil.setPushStreamServerIp(ip.replaceAll("-","."));
        return new Result(ResultCode.success,"成功",null);
    }

    @GetMapping("/setSRSIpWithGet")
    public Result setSRSIpWithGet(@RequestParam String ip){
        SRSUtil.setSrsServer_ip(ip.replaceAll("-","."));
        return new Result(ResultCode.success,"成功",null);
    }

    @PostMapping(value = "/callbackSave", produces = "application/json;charset=UTF-8")
    public void callbackSave(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        String body = "";
        try {
            Scanner scanner = new Scanner(request.getInputStream());
            scanner.useDelimiter("\\A");
            body = scanner.hasNext() ? scanner.next() : "";
            scanner.close();
        } catch (Exception ex) {
            writer.write("get request.getInputStream error:" + ex.getMessage());
            return;
        }
        if (body.isEmpty()) {
            writer.write("empty request.getInputStream");
            return;
        }
        JSONObject jsonObj = JSON.parseObject(body);
        System.out.println("回调参数对象 =====》》》 " + jsonObj);
        int status = (Integer) jsonObj.get("status");
        int saved = 0;
        //status=6,表示点击保存按钮
        if (status == 3 || status == 6) //MustSave, Corrupted
        {
            //获取url
            String downloadUri = (String) jsonObj.get("url");
            try {
                //获取onlyOffice缓存中的文件流
                URL url = new URL(downloadUri);
                java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                InputStream stream = connection.getInputStream();
                if (stream == null) {
                    throw new Exception("Stream is null");
                }
                String wjbh = request.getParameter("wjbh");
                if (StringUtils.isEmpty(wjbh)) {
                    throw new Exception("文件编号为空！！");
                }
               /* if (ObjectUtils.isEmpty(fileEntity)) {
                    throw new Exception("该文件不存在文件库中！！");
                }*/
                //上传新文件到文件服务器

                //根据文件编号获取文件对象

                //获取文件大小
                int size= connection.getContentLength();

                //重新设置文件对象属性并保存新文件到数据库

                connection.disconnect();
                //根据文件编号删除文件服务器的文件

            } catch (Exception ex) {
                saved = 1;
                ex.printStackTrace();
            }
        }
        writer.write("{\"error\":" + saved + "}");


    }

}
